package com.xjve.framework.hibernate.query.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjve.framework.hibernate.query.core.*;
import com.xjve.framework.hibernate.query.model.SqlQueryProperties;
import com.xjve.framework.hibernate.query.model.SqlTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * SQL查询自动配置类
 */
@Configuration
@ConditionalOnClass(SqlQueryDao.class)
@EnableConfigurationProperties(SqlQueryProperties.class)
public class SqlQueryAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(SqlQueryAutoConfiguration.class);

    @Bean
    @ConditionalOnMissingBean
    public SqlFileParser sqlFileParser(SqlQueryProperties properties) {
        logger.info("Creating SqlFileParser with location: {}", properties.getLocation());
        return new SqlFileParser(properties.getLocation());
    }


    @Bean
    @ConditionalOnMissingBean(name = "sqlTemplateEngine")
    public TemplateEngine sqlTemplateEngine(SqlFileParser sqlFileParser) {
        logger.info("Creating sql ThymeleafTemplateEngine");
        return new ThymeleafTemplateEngine(sqlFileParser.parseAllSqlFiles());
    }

    @Bean
    @ConditionalOnMissingBean
    public ParameterValidator parameterValidator() {
        logger.info("Creating ParameterValidator");
        return new ParameterValidator();
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlQueryDao sqlQueryDao(@Qualifier("sqlTemplateEngine") TemplateEngine sqlTemplateEngine,
                                   ParameterValidator parameterValidator,
                                   ObjectMapper objectMapper) {
        logger.info("Creating SqlQueryDao");
        return new SqlQueryDao(sqlTemplateEngine, parameterValidator, objectMapper);
    }
}
